<?php
/**
 * OSS配置测试脚本
 * 用于验证阿里云OSS配置是否正确
 */

require_once __DIR__ . '/vendor/autoload.php';
require_once __DIR__ . '/oss_config.php';

use AlibabaCloud\Oss\V2 as Oss;

try {
    // 获取配置
    $config = include __DIR__ . '/oss_config.php';

    echo "=== OSS配置测试 ===\n";
    echo "Access Key ID: " . substr($config['access_key_id'], 0, 8) . "...\n";
    echo "Region: " . $config['region'] . "\n";
    echo "Bucket: " . $config['bucket_name'] . "\n";
    echo "Endpoint: " . $config['endpoint'] . "\n\n";

// 使用StaticCredentialsProvider直接设置凭证（与上传代码保持一致）
    $credentialsProvider = new Oss\Credentials\StaticCredentialsProvider(
        $config['access_key_id'],
        $config['access_key_secret']
    );
    // 创建配置
    $cfg = new Oss\Config();
    $cfg->setCredentialsProvider($credentialsProvider);
    $cfg->setRegion($config['region']);
    $cfg->setEndpoint($config['endpoint']);
    $cfg->setConnectTimeout(30);
//    $cfg->setReadTimeout(30);

    // 禁用SSL验证（仅用于测试，生产环境建议使用正确的证书）
//    $cfg->setVerifySSL(false);

    // 创建客户端
    $client = new Oss\Client($cfg);

    echo "正在测试OSS连接...\n";

    // 测试列出bucket（这是一个简单的测试操作）
    $request = new Oss\Models\ListBucketsRequest();
    $result = $client->listBuckets($request);

    echo "✅ OSS连接成功！\n";
    echo "状态码: " . $result->statusCode . "\n";

//    var_dump($result->buckets);
    // 检查bucket是否存在
    $bucketExists = false;
    if (isset($result->buckets)) {

        foreach ($result->buckets as $bucket) {
            if ($bucket->name === $config['bucket_name']) {
                $bucketExists = true;
                break;
            }
        }
    }
    var_dump($bucketExists);
    if ($bucketExists) {
        echo "✅ Bucket '{$config['bucket_name']}' 存在\n";

        // 测试上传功能
        echo "\n正在测试上传功能...\n";
        $testContent = "这是一个测试文件，上传时间：" . date('Y-m-d H:i:s');
        $testKey = "test/" . time() . ".txt";

        try {
            $putRequest = new Oss\Models\PutObjectRequest($config['bucket_name'], $testKey);
            $putRequest->body = Oss\Utils::streamFor($testContent);
//            $putRequest->setContentType('text/plain');

            $putResult = $client->putObject($putRequest);

            if ($putResult->statusCode == 200) {
                echo "✅ 上传测试成功！\n";
                echo "测试文件路径: {$testKey}\n";

            } else {
                echo "❌ 上传测试失败，状态码: " . $putResult->statusCode . "\n";
            }
        } catch (Exception $e) {
            echo "❌ 上传测试失败！\n";
            echo "错误信息: " . $e->getMessage() . "\n";
            echo "错误代码: " . $e->getCode() . "\n";
        }
    } else {
        echo "❌ Bucket '{$config['bucket_name']}' 不存在或无权访问\n";
    }

} catch (Exception $e) {
    echo "❌ OSS连接失败！\n";
    echo "错误信息: " . $e->getMessage() . "\n";
    echo "错误代码: " . $e->getCode() . "\n";
    echo "错误类型: " . get_class($e) . "\n";

    // 输出详细的错误堆栈
    echo "错误堆栈:\n";
    echo $e->getTraceAsString() . "\n";

    if (strpos($e->getMessage(), 'SignatureDoesNotMatch') !== false) {
        echo "\n🔍 签名错误可能的原因：\n";
        echo "1. Access Key ID 或 Access Key Secret 不正确\n";
        echo "2. 系统时间不准确\n";
        echo "3. Region 配置错误\n";
        echo "4. 网络代理问题\n";
    }
}
?>
